package com.unlcn.ils.kas.service.order.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.unlcn.ils.kas.dao.model.order.TrackInfo;
import com.unlcn.ils.kas.service.order.GetTrackService;
import com.unlcn.ils.kas.service.order.TrackInfoService;
import com.unlcn.ils.kas.service.util.ErpUrl;
import com.unlcn.ils.kas.service.util.HttpClientUtil;
import com.unlcn.ils.kas.service.util.enums.WebServiceUrlEnum;
import com.unlcn.ils.kas.service.webservice.ServiceLocator;
import com.unlcn.ils.kas.service.webservice.ServiceSoapStub;
import org.apache.http.NameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class GetTrackServiceImpl implements GetTrackService {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetTrackServiceImpl.class);

    @Autowired
    private TrackInfoService trackInfoService;

    @Autowired
    private ErpUrl erpUrl;

    @Override
    public void getTrack() {

        // 请求 erp 在途数据
        List<NameValuePair> orderParams = new ArrayList<>();
        Date callStartTime = new Date();
        String trackInfo = HttpClientUtil.get(erpUrl.getGetErpTrack(), orderParams, 600000000);
        Date callEndTime = new Date();
        List<TrackInfo> trackInfoList = getData(trackInfo);
        LOGGER.info("拉取到" + trackInfoList.size() + "条在途信息");
        if (CollectionUtils.isEmpty(trackInfoList))
            return;

        // 上传民生物流
        String result = uploadOrder(trackInfoList);
        LOGGER.info("上传民生物流返回信息: " + result);
        if (result == null)
            return;

        Integer flag = null;
        if (result.equals("成功")) {
            flag = 1;
        } else {
            flag = 0;
        }

        // 保存日志表
        for (TrackInfo data : trackInfoList) {
            data.setFlag(flag);
            data.setCallStartTime(callStartTime);
            data.setCallEndTime(callEndTime);
        }
        trackInfoService.insertBatch(trackInfoList);
    }

    @Override
    public String uploadOrder(List<TrackInfo> trackInfoList) {

        String result = null;

        try {

            String[] gpsOnway = new String[trackInfoList.size()];

            for (int i=0; trackInfoList.size()>i; i++) {

                TrackInfo trackInfo = trackInfoList.get(i);
                StringBuilder data = new StringBuilder();

                // 车牌
                data.append(trackInfo.getLicensePlate() + ",");
                // 承运商
                data.append(trackInfo.getSupplier() + ",");

                // 经度
                if (!StringUtils.isEmpty(trackInfo.getLongitude())) {
                    if (trackInfo.getLongitude().length() > 9) {
                        String longitude = trackInfo.getLongitude().substring(0, 9);
                        trackInfo.setLongitude(longitude);
                    }
                    data.append(trackInfo.getLongitude() + ",");
                } else {
                    data.append(",");
                }

                // 纬度
                if (!StringUtils.isEmpty(trackInfo.getLatitude())) {
                    if (trackInfo.getLatitude().length() > 9) {
                        String latitude = trackInfo.getLatitude().substring(0, 9);
                        trackInfo.setLatitude(latitude);
                    }
                    data.append(trackInfo.getLatitude() + ",");
                } else {
                    data.append(",");
                }

                // 地点
                data.append(trackInfo.getAddress() + ",");
                // 时间
                data.append(trackInfo.getTrackTime() + ",");
                // 地点描述
                data.append(trackInfo.getAddressDesc() + ",");
                // 采集方式
                data.append(trackInfo.getType() + ",");
                // 到达标志
                data.append(trackInfo.getArrvieFlag() + ",");
                // 速度
                data.append(trackInfo.getSpeed());

                gpsOnway[i] = data.toString();
            }

            ServiceLocator locator = new ServiceLocator();
            ServiceSoapStub stub = (ServiceSoapStub) locator.getServiceSoap();
            result = stub.insert_GpsOnway_info_add(gpsOnway);
        } catch (Exception e) {
            LOGGER.error("GetTrackServiceImpl.uploadOrder ERROR ", e);
        }

        return result;
    }

    @Override
    public List<TrackInfo> getData(String result) {

        List<TrackInfo> trackInfoList = new ArrayList<>();

        JSONObject json = JSONObject.parseObject(result);

        if (json==null || json.get("data")==null)
            return trackInfoList;

        JSONArray jsonArray = new JSONArray();

        if (json.get("data") != null) {
            jsonArray = JSONArray.parseArray(json.get("data").toString());
        }

        for (Object object : jsonArray) {

            TrackInfo trackInfo = new TrackInfo();
            Map map = (Map)object;

            // 车牌号
            trackInfo.setLicensePlate(map.get("vclicense")==null?""
                    :map.get("vclicense").toString());
            // 承运商
            trackInfo.setSupplier(map.get("vcsupplier")==null?""
                    :map.get("vcsupplier").toString());
            // 经度
            trackInfo.setLongitude(map.get("vclongitude")==null?""
                    :map.get("vclongitude").toString());
            // 纬度
            trackInfo.setLatitude(map.get("vclatitude")==null?""
                    :map.get("vclatitude").toString());
            // 地点
            trackInfo.setAddress(map.get("vclocation")==null?""
                    :map.get("vclocation").toString());
            // 时间
            trackInfo.setTrackTime(map.get("dtlocation")==null?null
                    :map.get("dtlocation").toString());
            // 地点描述
            trackInfo.setAddressDesc(map.get("vcmemo")==null?""
                    :map.get("vcmemo").toString());
            // 采集方式
            trackInfo.setType(map.get("vctype")==null?""
                    :map.get("vctype").toString());
            // 到达标志
            trackInfo.setArrvieFlag(map.get("vcarrvie_flag")==null?""
                    :map.get("vcarrvie_flag").toString());
            // 速度
            trackInfo.setSpeed(map.get("vcspeed")==null?""
                    :map.get("vcspeed").toString());
            // 创建时间
            trackInfo.setGmtCreate(new Date());
            // 上传时间
            trackInfo.setUploadTime(new Date());
            // 获取数据地址
            trackInfo.setCallUrl(erpUrl.getGetErpTrack());
            // 获取上传地址
            trackInfo.setUploadUrl(WebServiceUrlEnum.MSH_URL.getValue());

            trackInfoList.add(trackInfo);
        }

        return trackInfoList;
    }
}
